package fr.umlv.m2.jee.pmlv.web.professor;

import fr.umlv.m2.jee.pmlv.persistence.cursus.Specialty;
import fr.umlv.m2.jee.pmlv.persistence.cursus.SpecialtySubject;
import fr.umlv.m2.jee.pmlv.service.cursus.DisplayCursus;
import fr.umlv.m2.jee.pmlv.service.cursus.IDisplayCursusService;
import fr.umlv.m2.jee.pmlv.service.note.DisplayUserNote;
import fr.umlv.m2.jee.pmlv.service.note.IDisplayUserNoteService;
import fr.umlv.m2.jee.pmlv.service.subject.IDisplaySubjectService;
import fr.umlv.m2.jee.pmlv.service.user.User;
import fr.umlv.m2.jee.pmlv.service.user.impl.UserService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.naming.NamingException;
import javax.servlet.ServletContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Servlet wich represents the student's list of a professor.
 * @author Alexandre
 */
public class ListOfStudents extends HttpServlet {
    // Variables
    private static final int MAX_STUDENT_BY_PAGE = 15;
    private User user = null;   //Contains informations about user
    private List<Integer> years = new ArrayList<Integer>(); //Contains years when professor teaching a subject
    private int currentYear = -1;   //the current year

    private List<DisplayCursus> cursus = new ArrayList<DisplayCursus>();    //Subjects teached by user
    private Long idSubject = Long.valueOf("-1");    //Identifiant of subject selected
    private List<User> students = new ArrayList<User>();    //Students who follow subject selected
    private Map<String, DisplayUserNote> notes = new HashMap<String, DisplayUserNote>();    //Notes of students for subject selected
    private int page = 0;   //Current page of pagination



    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListOfStudents() {
            super();
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response).
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doPost(request,response);
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response).
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //Data
        user = null;
        years.clear();
        currentYear = -1;
        cursus.clear();
        idSubject = Long.valueOf("-1");
        students.clear();
        notes.clear();
        page = 0;


        //Retrieve informations about user
        HttpSession session = request.getSession(true);
        user = (User)session.getAttribute("user");
        years.addAll((List<Integer>)session.getAttribute("years"));
        if(Calendar.getInstance(Locale.FRENCH).get(Calendar.MONTH)>9) currentYear = Calendar.getInstance(Locale.FRENCH).get(Calendar.YEAR);
        else currentYear = Calendar.getInstance(Locale.FRENCH).get(Calendar.YEAR) - 1;

        //Retrieve list of subjects teached by user for current year
        ServletContext context = getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
        IDisplayCursusService cursusService = (IDisplayCursusService) applicationContext.getBean("defautDisplayCursusService");
        cursus.addAll(cursusService.getCursusByProfessorUidAndByYear(user.getuId(), currentYear));

        //Retrieve filter selected and students
        if(request.getParameter("subject")!=null)
        {
            idSubject = Long.parseLong(request.getParameter("subject"));
            //Retrieve list of students who follow subjects teach by user, statut of user for subject selected
            UserService userService = (UserService) applicationContext.getBean("ldapUser");
            try {
                students.addAll(userService.getStudentBySubjectIdAndByYear(idSubject, currentYear));
            } catch (NamingException ex) { }
            //retrieve notes of all students for subject selected
            IDisplayUserNoteService noteService = (IDisplayUserNoteService) applicationContext.getBean("defautDisplayUserNoteService");
            List<DisplayUserNote> tmpNotes = noteService.getNoteBySubjectAndByYear(idSubject,currentYear);
            for(DisplayUserNote note:tmpNotes)
            {
                notes.put(note.getUid(), note);
            }
            //Retrieve page for list of students
            if(request.getParameter("page")!=null)
                page = Integer.parseInt(request.getParameter("page"));
            //Retrieve page
            session.setAttribute("back", getServletContext().getContextPath()+"/Professor/ListOfStudents?subject="+idSubject+"&page="+page);
        }


        //View
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\" >");

        out.println(" <head>");
        out.println("   <title>PMLV : Portail Universitaire de Marne-La-Vall&eacute;e </title>");
        out.println("   <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />");
        out.println("   <link rel=\"stylesheet\" media=\"screen\" type=\"text/css\" href=\"../css/professor/professor.css\" />");
        out.println("   <link rel=\"stylesheet\" media=\"screen\" type=\"text/css\" href=\"../css/professor/listOfStudents.css\" />");
        out.println(" </head>");

        out.println(" <body>");

        out.println("   <div id=\"header\">");
        out.println("     <ul>");
        out.println("       <li class=\"menuItem menuItemSpacing\"><a href=\"../Professor\">Accueil</a></li>");
        out.println("       <li class=\"menuItem menuItemSpacing\"><a href=\"ListOfStudents\">Listes des &eacute;tudiants</a></li>");
        out.println("       <li class=\"menuItem menuItemSpacing cursor\">Emploi du temps");
        out.println("         <ul class=\"subMenuBar\">");
        out.println("           <li class=\"subMenu\"><a href=\"ScheduleOfCoursesAndExams\">Cours et examens</a></li>");
        out.println("           <li class=\"subMenu\"><a href=\"ScheduleOfWorksToMake\">Rendu de travaux</a></li>");
        out.println("         </ul>");
        out.println("       </li>");
        out.println("       <li class=\"menuItem menuItemSpacing cursor\">Gestion de mati&egrave;re");
        out.println("         <ul class=\"subMenuBar\">");
        for(Integer year:years)
        {
            out.println("           <li class=\"subMenu\"><a href=\"ManagementOfSubjects?year="+year+"\">"+ year +"-"+ (year+1) +"</a></li>");
        }
        out.println("         </ul>");
        out.println("       </li>");
        out.println("       <li id=\"menuItemMargin\" class=\"menuItem\"><a href=\"../j_spring_security_logout\">Se d&eacute;connecter</a></li>");
        out.println("     </ul>");
        out.println("   </div>");

        getDivContent(out, request, response);

        out.println("   <div id=\"footer\">");
        out.println("     <div id=\"copyright\">&copy; Universit&eacute; Paris-Est Marne-la-Vall&eacute;e</div>");
        out.println("     <div>PMLV v1.0 </div>");
        out.println("   </div>");

        out.println(" </body>");

        out.println("</html>");
        out.close();
    }

    /**
     *  Content of page
     */
    private void getDivContent(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
    {
        out.println("   <div id=\"content\">");

        //Title
        if(idSubject==-1)
            out.println("     <div id=\"title\">Liste des &eacute;tudiants par mati&egrave;re</div>");
        else
        {
            ServletContext context = getServletContext();
            WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
            IDisplaySubjectService subService = (IDisplaySubjectService) applicationContext.getBean("defautDisplaySubjectService");
            out.println("     <div id=\"title\">Liste des &eacute;tudiants inscrit en "+subService.getDisplaySubjectbyId(idSubject).getName()+"</div>");
        }

        //Menu
        out.println("       <table id=\"menu\">");
        for(DisplayCursus c:cursus)
        {
            out.println("         <tr><td colspan=\"2\"><li>"+ c.getName() +"</li></td></tr>");
            for(Specialty spe:c.getSpecialties())
            {
                out.println("         <tr>");
                out.println("           <td class=\"speciality\"><li> "+ spe.getName() +"</li></td>");
                out.println("           <td class=\"arrow\"></td>");
                out.println("         </tr>");
                for(SpecialtySubject sub:spe.getSpecialtySubject())
                {
                    out.println("         <tr>");
                    out.println("           <td class=\"subject\"><li> "+ sub.getSubject().getName() +"</li></td>");
                    out.println("           <td class=\"arrow\"><a href=\"ListOfStudents?subject="+ sub.getSubject().getId() +"\"><img src=\"../images/next.jpg\"/></a></td>");
                    out.println("         </tr>");
                }
            }
        }
        out.println("       </table>");

        
        //List of students
        if(idSubject!=-1)
        {
            out.println("         <table id=\"listOfStudentsBySubjectTable\">");
            out.println("           <tr>");
            out.println("             <th>Num&eacute;ro d'&eacute;tudiant</th>");
            out.println("             <th>Nom</th>");
            out.println("             <th>Pr&eacute;nom</th>");
            out.println("             <th>Moyenne</th>");
            out.println("           </tr>");
            for(int i=0;i<MAX_STUDENT_BY_PAGE;i++)
            {
                int j = (page*MAX_STUDENT_BY_PAGE)+i;
                if(i%2 == 0) out.println("           <tr class=\"tableLightBackground\">");
                else out.println("           <tr class=\"tableDarkBackground\">");
                if(j<students.size())
                {
                    out.println("             <td>"+ students.get(j).getNumber() +"</td>");
                    out.println("             <td>"+ students.get(j).getLastname() +"</td>");
                    out.println("             <td>"+ students.get(j).getFirstname() +"</td>");
                    if(notes.containsKey(students.get(j).getuId()) && notes.get(students.get(j).getuId()).getNote()!=null)
                        out.println("             <td>"+ notes.get(students.get(j).getuId()).getNote() +"</td>");
                    else
                        out.println("             <td> &nbsp </td>");
                    out.println("           </tr>");
                }
                else
                {
                    out.println("             <td> &nbsp </td>");
                    out.println("             <td> &nbsp </td>");
                    out.println("             <td> &nbsp </td>");
                    out.println("             <td> &nbsp </td>");
                    out.println("           </tr>");
                }
            }
            //Pagination
            out.println("           <tr>");
            if((students.size()/MAX_STUDENT_BY_PAGE==0) || (students.size()/MAX_STUDENT_BY_PAGE==1 && students.size()%MAX_STUDENT_BY_PAGE==0))
            {
                out.println("             <th colspan=\"4\"> &nbsp </th>");
            }
            else
            {
                out.println("             <th colspan=\"4\">");
                for(int i=0;i<students.size()/MAX_STUDENT_BY_PAGE;i++)
                {
                    if(i==page)
                        out.println("             "+(i+1));
                    else
                        out.println("             <a href=\"ListOfStudents?subject="+idSubject+"&page="+i+"\">"+(i+1)+"</a>");
                }
                if(students.size()%MAX_STUDENT_BY_PAGE!=0 && page==students.size()/MAX_STUDENT_BY_PAGE)
                    out.println("             "+((students.size()/MAX_STUDENT_BY_PAGE)+1));
                else if(students.size()%MAX_STUDENT_BY_PAGE!=0)
                    out.println("             <a href=\"ListOfStudents?subject="+idSubject+"&page="+(students.size()/MAX_STUDENT_BY_PAGE)+"\">"+((students.size()/MAX_STUDENT_BY_PAGE)+1)+"</a>");
                out.println("             </th>");
            }
            out.println("           </tr>");
            out.println("           <tr> <td> &nbsp </td> </tr>");
            out.println("         </table>");
        }
        
        out.println("   </div>");
    }
}
